<?php
/**
 * Controller pre admin-user
 * @author Tomas Srna
 * @package bakalarka
 */

class AdminUserController extends Controller 
{
	protected $resource = 'admin-user';
	
	/**
	 * Akcia index
	 */
	public function index()
	{
		$t = Template::instance();
		
		$dv = new DynamicView();
		$dv->buttonAdd = true;
		$dv->primaryKeys = array('username');
		$dv->baseUrl = APPBASE."admin/user";
		$dv->passwd = true;
		
		$dv->itemCount = Selector::select("count(*) as c")->from('user')
			->fetch()->current()->c;
		
		$t->dv = $dv;
		$t->dvw = new DynamicViewWriter($t->dv, $t);
		
		$t->title = L::selected()->userAdmin;
		$t->text = "";
		
		$t->render('dynamic-view');
	}
	
	/**
	 * Akcia data
	 */
	public function data()
	{
		$params = $_GET;
		
		$t = Template::instance();
		
		// Kontrola vstupov
		$by_possible = array(	"username", "email", "group", "firstname", 
								"lastname", "phone", "address");
		
		$dt = new DynamicTable();
		$dt->primaryKeys = array('username');
		$dt->itemCount = Selector::select("count(*) as c")->from('user')
			->fetch()->current()->c;
		
		$dt->buttons = array(
			new Button('pencil.png', L::selected()->edit, 
				"act('edit', false, %params%)"),
			new Button('key.png', L::selected()->passwd, 
				"act('passwd', false, %params%)"),
			new Button('delete.png', L::selected()->delete, 
				"act('delete', true, %params%)"),
		);
		
		if(!$dt->check($params, $by_possible))
			$t->error = L::selected()->invalidInput;
		
		if(!property_exists($t, 'error'))
		{
			$dt->headers['username'] = L::selected()->username;
			$dt->headers['email'] = L::selected()->email;
			$dt->headers['group'] = L::selected()->group;
			$dt->headers['firstname'] = L::selected()->firstname;
			$dt->headers['lastname'] = L::selected()->lastname;
			
			$dt->passwd = true;
			
			if(!array_key_exists('page', $params))
				$params['page'] = 1;
			
			$select = Selector::select()
						->from(UserModel::struct())
						->page($params['page'])
						->by($params);
			
			$dt->data = $select->fetch();
			
			$t->dtw = new DynamicTableWriter($dt, $t);
		}
	
		$t->dt = $dt;
		$t->render('dynamic-table');
	}

	/**
	 * Akcia edit
	 * @param bool $create		Vytvarame noveho uzivatela?
	 */
	public function edit($create = false)
	{
		$t = Template::instance();
		
		if($create)
		{
			$t->title = L::selected()->createUser;
			if(getenv('REQUEST_METHOD') == 'POST')
				$model = UserModel::create($_POST);
			else
				$model = NULL;
		}
		else
		{
			$t->title = L::selected()->editUser;
			
			// Skontrolujeme ci existuje objekt a nacitame ho
			if(!array_key_exists('username', $_GET))
				throw new Exception('L::errorObjectNotFound;'.
						json_encode(array('UserModel(?)')));
						
			$model = UserModel::load(array('username' => $_GET['username']));
			if(!$model)
				throw new Exception('L::errorObjectNotFound;'.
					json_encode(array(sprintf('UserModel(%s)', $_GET['username']))));
		}
		
		if(getenv('REQUEST_METHOD') == 'POST')
		{
			$f = new UserForm($t, $_POST);
			
			if($f->validate())
			{
				// Kontrola duplicity
				if($create)
					$dup = UserModel::load(array(
						'username' => $_POST['username']
					));
				
				if(!$create || $dup == NULL)
				{
					if(!$create)
					{
						// Username nesmieme menit
						if(array_key_exists('username', $_POST))
							unset($_POST['username']);
						$model->set($_POST);
					}
					$model->save();
					if($create)
						Logger::log('L::objectCreated_s;'.
							json_encode((string)$model), 'info');
					else
						Logger::log('L::objectChanged_s;'.
							json_encode((string)$model), 'info');
					$this->autoredir();
				}
				else
					$t->error = L::selected()->duplicity;
			}
			else
				$t->error = L::selected()->invalidForm;
		}
		else
		{
			$f = new UserForm($t, $model);
		}
		
		$fw = new FormWriter($f);
		$t->fw = $fw;
		
		$t->render('form');
	}

	/**
	 * Vytvorenie noveho uzivatela
	 */
	public function create()
	{
		// Zavolame edit s $create = true
		return $this->edit(true);
	}

	/**
	 * Zmena hesla
	 */
	public function passwd()
	{
		$t = Template::instance();
		$t->title = L::selected()->passwordChange;
					
		// Skontrolujeme ci existuje objekt a nacitame ho
		if(!array_key_exists('username', $_GET))
			throw new Exception('L::errorObjectNotFound;'.
					json_encode(array('UserModel(?)')));
					
		$model = UserModel::load(array('username' => $_GET['username']));
		if(!$model)
			throw new Exception('L::errorObjectNotFound;'.
				json_encode(array(sprintf('UserModel(%s)', $_GET['username']))));
		
		if(getenv('REQUEST_METHOD') == 'POST')
		{
			$f = new PasswdForm($t, $_POST);
			
			if($f->validate())
			{
				$model->password_hash = hash(Config::$hash_function, 
					$_POST['password']);
				
				$model->save();
				Logger::log('L::objectChanged_s;'.
					json_encode((string)$model), 'info');
				
				$this->autoredir();
			}
			else
				$t->error = L::selected()->invalidForm;
		}
		else
		{
			$f = new PasswdForm($t, $model);
		}
		
		$fw = new FormWriter($f);
		
		$t->fw = $fw;
		
		$t->render('form');
	}

	/**
	 * Odstranenie riadka
	 */
	public function delete()
	{
		// Skontrolujeme ci existuje objekt a nacitame ho
		if(!array_key_exists('username', $_GET))
			throw new Exception('L::errorObjectNotFound;'.
					json_encode(array('UserModel(?)')));
					
		$model = UserModel::load(array('username' => $_GET['username']));
		if(!$model)
			throw new Exception('L::errorObjectNotFound;'.
				json_encode(array(sprintf('UserModel(%s)', $_GET['username']))));
				
		// Zmazeme vsetky zavislosti
		Selector::select()->from(AclModel::struct())->where('role = ?',
			$model->username)->delete();
		
		// Zmazeme samotny riadok
		$model->delete();
		Logger::log('L::objectDeleted_s;'.
			json_encode((string)$model), 'info');
		
		$this->autoredir();
	}
}
